﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GUI.PaginationControl
{
    [Category("Behavior")]
    [ToolboxData("<{0}:PaginationControl runat=server></{0}:PaginationControl>")]
    public class PaginationControl : WebControl
    {
        public int CurrentPage { get; set; }
        public int ResultsPerPage { get; set; }
        public int PagesShown { get; set; }
        public int TotalResults { get; set; }
        public string PageURI { get; set; }
        public string QueryStringParam { get; set; }

        protected override void Render(HtmlTextWriter writer)
        {
            int maxPages = TotalResults / ResultsPerPage;
            int startPage = CurrentPage - (PagesShown / 2);
            int endPage = CurrentPage + (PagesShown / 2);

            if (endPage >= maxPages)
            {
                endPage = maxPages;
                startPage = endPage - PagesShown;
            }

            startPage = startPage <= 0 ? 1 : startPage;

            //Render
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "pagination");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            for (int i = startPage; i <= endPage; ++i)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Href, string.Format("{0}?{1}={2}", PageURI, QueryStringParam, i));
                if (i == CurrentPage)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "current");
                }

                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.InnerWriter.Write(i);
                writer.RenderEndTag();
            }
            writer.RenderEndTag();
        }
    }
}
